package com.xinpan.exercise;

public class ValidNumber {
    public boolean isNumber(String s) {
        // Start typing your Java solution below
        // DO NOT write main() function
        
        if(s == null)
            return false;
        s = s.trim();
        if(s.length() == 0)
            return false;
            
        for(int i = 0; i < s.length(); i++)
        {
            char v = s.charAt(i);
            
            if(i == 0 && (v == '+' || v == '-'))
                continue;
            else if(v == '.')
            {
                if(isInt(s.substring(0, i)) && isFrac(s.substring(i+1, s.length())))
                    return true;
                else
                    return false;
            }
            else if(v == 'e')
            {
                if(isNumber(s.substring(0, i)) && isInt(s.substring(i+1, s.length())))
                    return true;
                else
                    return false;
            }
            else if(v == '0' && i == 0)
            {
                if(isBinary(s))
                    return true;
                if(s.length() == 1)
                    return true;
                if(s.charAt(i+1) == '.' && isFrac(s.substring(i+2, s.length())))
                    return true;
                else
                    return false;
            }
            else if(v > '0' && v <= '9')
                continue;
            else
                return false;
        }
        return true;
    }
    public boolean isBinary(String s)
    {
        s = s.trim();
        for(int i = 0; i < s.length(); i++)
        {
            char v = s.charAt(i);
            if(v != '0' && v != '1')
                return false;
        }
        return true;
    }
    public boolean isInt(String s)
    {
        if(s == null || s.length() == 0)
            return false;
        
        for(int i = 0; i < s.length(); i++)
        {
            char v = s.charAt(i);
            if(v == '0')
                if(i == 0)
                    return false;
                else
                	continue;
            else if(v > '0' && v <= '9')
                continue;
            else if(v == 'e')
                return isInt(s.substring(i+1, s.length()));
            else
                return false;
        }
        return true;
    }
    public boolean isFrac(String s)
    {
        if(s == null)
            return true;
        
        for(int i = 0; i < s.length(); i++)
        {
            char v = s.charAt(i);

            if(v >= '0' && v <= '9')
                continue;
            else
                return false;
        }
        return true;
    }
    
    public static void main(String[] args)
    {
    	ValidNumber vn = new ValidNumber();
    	vn.isNumber("2e10");
    }
}
